﻿/*************************************************************************
 *  Copyright (C), 2017-2018, YangTao tech. Co., Ltd.
 *  FileName: ServerPanelScrp.cs
 *  Author: YangTao   Version: 1.0   Date: 11/28/2016
 *  Email:YangTao_Unity3D@163.com
 *  Version Description:
 *    
 *  File Description:
 *    
 *  Class List:
 *    <ID>           <name>             <description>
 *     1.         ServerPanelScrp             
 *  Function List:
 *    <class ID>     <name>             <description>
 *     1.
 *  History:
 *    <ID>    <author>      <time>      <version>      <description>
 *     1.     YangTao     11/28/2016       1.0        Build this file.
 *************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ServerPanelScrp : MonoBehaviour
{
    SocketServer m_server;
    /// <summary>消息显示</summary>
    public UILabel m_showText;
    /// <summary>消息输入</summary>
    public UIInput m_msgInput;
    /// <summary>分组名字</summary>
    public UIInput m_NameInput;
    /// <summary>启动按钮</summary>
    public UIButton m_startBtn;
    /// <summary>发送按钮</summary>
    public UIButton m_sendBtn;
    /// <summary>选择所有客户端按钮</summary>
    public UIButton m_allClientBtn;
    /// <summary>Open按钮</summary>
    public UIButton m_openBtn;
    /// <summary>CreatButton按钮</summary>
    public UIButton m_creatGroupBtn;
    /// <summary>Group按钮</summary>
    public UIButton m_groupBtn;
    /// <summary>Creat按钮</summary>
    public UIButton m_creat;
    /// <summary>显示消息链表</summary>
    public UITextList m_textList;
    /// <summary>发送的消息</summary>
    string m_sendString;
    /// <summary>消息</summary>
    string m_content;
    /// <summary>发送方客户端ip</summary>
    string m_clientNameFrom;
    /// <summary>被发送方客户端ip</summary>
    string m_clientNameTo;
    /// <summary>客户端Grid</summary>
    public UIGrid m_clientGrid;
    /// <summary>分组客户端Grid</summary>
    public UIGrid m_groupClientGrid;
    /// <summary>选择分组客户端Grid</summary>
    public UIGrid m_selectClientGrid;
    /// <summary>分组Grid</summary>
    public UIGrid m_groupGrid;
    /// <summary>客户端Button</summary>
    public GameObject m_clientButton;
    /// <summary>分组客户端Button</summary>
    public GameObject m_groupClientButton;
    /// <summary>已连接客户端IP</summary>
    string m_addClientIP;
    /// <summary>删除的客户端IP</summary>
    List<string> m_deletClientIP;
    /// <summary>已连接客户端</summary>
    Dictionary<string, ClickClientButton> m_clientButtonDic;
    /// <summary>已连接客户端</summary>
    Dictionary<GameObject, string> m_clientButtonObjDic;
    /// <summary>已连接客户端</summary>
    Dictionary<string, GroupClickClientButton> m_groupClientButtonDic;
    /// <summary>已连接客户端</summary>
    Dictionary<GameObject, string> m_groupClientButtonObjDic;
    /// <summary>客户端组</summary>
    Dictionary<GameObject, List<string>> m_clientGroupDic;
    /// <summary>已连接客户端列表</summary>
    public GameObject m_clientScroll;
    /// <summary>分组列表</summary>
    public GameObject m_clientGroupScroll;
    /// <summary>分组界面</summary>
    public GameObject m_groupingPanel;
    /// <summary>分组界面内容</summary>
    public GameObject m_information;
    /// <summary>分组已连接客户端列表</summary>
    public UIScrollView m_groupClientScroll;
    /// <summary>已选择客户端列表</summary>
    public UIScrollView m_selectClientScroll;
    /// <summary>是否显示已连接客户端</summary>
    bool m_isShowClientList;
    /// <summary>是否显示创建组界面</summary>
    bool m_isShowCreatGroup;
    /// <summary>是否显示分组界面</summary>
    bool m_isShowGroup;
    /// <summary>已选择客户端</summary>
    List<string> m_alreadySelectedCli;
    /// <summary>客户端下拉列表</summary>
    public GameObject m_clientList;
    /// <summary>客户端分组下拉列表</summary>
    public GameObject ClientGroupList;
    /// <summary>是否选择所有客户端</summary>
    bool m_isSelect;
    /// <summary>客户端Button</summary>
    public List<GameObject> m_buttonList;

    void Start()
    {
        Init();
    }

    /// <summary>初始化</summary>
    void Init()
    {
        m_sendString = "";
        UIEventListener.Get(m_startBtn.gameObject).onClick += StartServer;
        UIEventListener.Get(m_sendBtn.gameObject).onClick += SendMessage;
        UIEventListener.Get(m_openBtn.gameObject).onClick += OpenClientList;
        UIEventListener.Get(m_allClientBtn.gameObject).onClick += SelectAllClient;
        UIEventListener.Get(m_creatGroupBtn.gameObject).onClick += OpenCreatGroup;
        UIEventListener.Get(m_groupBtn.gameObject).onClick += OpenGroup;
        UIEventListener.Get(m_creat.gameObject).onClick += CreatGroup;
        m_server = new SocketServer();
        m_server.Init();
        m_server.m_cliManage.AddNewClientCallback = AddClient;
        m_server.DeletClientCallback = DeletClient;
        m_server.ReceiveMsgCallback = ReceiveMessage;
        m_content = "";
        m_addClientIP = "";
        m_deletClientIP = new List<string>();
        m_clientButtonDic = new Dictionary<string, ClickClientButton>();
        m_clientButtonObjDic = new Dictionary<GameObject, string>();
        m_groupClientButtonDic = new Dictionary<string, GroupClickClientButton>();
        m_groupClientButtonObjDic = new Dictionary<GameObject, string>();
        m_clientGroupDic = new Dictionary<GameObject, List<string>>();
        m_isShowClientList = true;
        m_isShowCreatGroup = true;
        m_isShowGroup = true;
        m_alreadySelectedCli = new List<string>();
        m_isSelect = true;
    }

    void Update()
    {
        ClientButtonManage();
        ShowMsg();
    }

    /// <summary>消息显示</summary>
    void ShowMsg()
    {
        if (m_content != "")
        {
            m_textList.Add("[00ffff]" + m_clientNameFrom + " " + "[-]" + "Said to" + " " + "[8bddfc]" + m_clientNameTo + ":" + "[-]" + m_content);
            m_content = "";
        }
        else m_clientNameTo = "";
    }

    /// <summary>客户端Button管理</summary>
    void ClientButtonManage()
    {
        if (m_addClientIP != "")
        {
            //Connected Client************************************************************************
            GameObject obj = NGUITools.AddChild(m_clientGrid.gameObject, m_clientButton);
            ClickClientButton ccb = obj.GetComponent<ClickClientButton>();

            ////处理网格的事务        
            m_clientGrid.repositionNow = true;

            //处理客户端Item事务
            ccb.m_clientIPLabel.text = m_addClientIP;
            UIEventListener.Get(ccb.gameObject).onClick = ClickClientItem;

            m_clientButtonDic.Add(m_addClientIP, ccb);
            m_clientButtonObjDic.Add(ccb.gameObject, m_addClientIP);

            //Grouping*********************************************************************************
            GameObject obj1 = NGUITools.AddChild(m_groupClientGrid.gameObject, m_groupClientButton);
            GroupClickClientButton gccb = obj1.GetComponent<GroupClickClientButton>();

            ////处理网格的事务        
            m_groupClientGrid.repositionNow = true;

            //处理客户端Item事务
            gccb.m_clientIPLabel.text = m_addClientIP;
            UIEventListener.Get(gccb.gameObject).onClick = GroupClickClientItem;

            m_groupClientButtonDic.Add(m_addClientIP, gccb);
            m_groupClientButtonObjDic.Add(gccb.gameObject, m_addClientIP);

            m_addClientIP = "";
        }
        if (m_deletClientIP.Count > 0)
        {
            //Connected Client************************************************************************
            for (int i = 0; i < m_deletClientIP.Count; i++)
            {
                GameObject item = m_clientButtonDic[m_deletClientIP[i]].gameObject;

                m_clientButtonDic.Remove(m_deletClientIP[i]);
                m_clientButtonObjDic.Remove(item);

                Destroy(item);

                //Grouping*********************************************************************************
                GameObject item1 = m_groupClientButtonDic[m_deletClientIP[i]].gameObject;

                m_groupClientButtonDic.Remove(m_deletClientIP[i]);
                m_groupClientButtonObjDic.Remove(item1);

                Destroy(item1);
            }
            m_clientGrid.repositionNow = true;
            m_clientGrid.repositionNow = true;
            m_deletClientIP.Clear();
        }
    }

    /// <summary>点击客户端button</summary>
    void ClickClientItem(GameObject go)
    {
        string ip;
        if (m_clientButtonObjDic.TryGetValue(go, out ip))
        {
            ClickClientButton ccb;
            if (m_clientButtonDic.TryGetValue(ip, out ccb))
            {
                if (ccb.m_isAdd)
                {
                    m_alreadySelectedCli.Add(ccb.m_clientIPLabel.text);
                }
                else
                {
                    m_alreadySelectedCli.Remove(ccb.m_clientIPLabel.text);
                }
            }
        }
    }

    /// <summary>点击客户端button</summary>
    void GroupClickClientItem(GameObject go)
    {
        bool IsSelect = go.GetComponent<GroupClickClientButton>().m_isSelect;
        if (!IsSelect)
        {
            m_selectClientGrid.AddChild(go.transform);
            //go.GetComponent<UIDragScrollView>().scrollView = m_selectClientScroll;
            m_selectClientGrid.repositionNow = true;
            m_groupClientGrid.repositionNow = true;
            go.GetComponent<GroupClickClientButton>().m_isSelect = true;
        }
        else
        {
            m_groupClientGrid.AddChild(go.transform);
            //go.GetComponent<UIDragScrollView>().scrollView = m_groupClientScroll;
            m_selectClientGrid.repositionNow = true;
            m_groupClientGrid.repositionNow = true;
            go.GetComponent<GroupClickClientButton>().m_isSelect = false;
        }
    }

    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="go"></param>
    void StartServer(GameObject go)
    {
        if (m_server.InitNetwork())
        {
            m_textList.Add("[8bddfc]Server starts successfully![-]");
        }
        else
            m_textList.Add("[8bddfc]Server is connected![-]");
    }

    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="clientName">发送方IP</param>
    /// <param name="str">收到的消息（去头）</param>
    /// <param name="list">被发送方list</param>
    void ReceiveMessage(string clientName, string str, List<string> list)
    {
        m_content = str;
        m_clientNameFrom = clientName;
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i] == m_server.m_serverIP + ":8888")
            {
                list[i] = "Server";
            }
            m_clientNameTo += list[i] + " " + "||" + " ";
        }
        m_clientNameTo = m_clientNameTo.Remove((m_clientNameTo.Length - 3));

    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="go"></param>
    void SendMessage(GameObject go)
    {
        m_sendString = m_msgInput.value;
        if (m_alreadySelectedCli.Count > 0 && m_sendString != "")
        {
            m_server.SendContent(m_alreadySelectedCli, m_sendString);
            string ipStr = "";
            for (int i = 0; i < m_alreadySelectedCli.Count; i++)
            {
                ipStr += m_alreadySelectedCli[i] + " " + "||" + " ";
            }
            ipStr = ipStr.Remove(ipStr.Length - 3);
            m_textList.Add("[00ffff]I[-]" + " " + "said to " + "[8bddfc]" + " " + ipStr + "[-]" + ":" + m_sendString);
            m_msgInput.value = "";//清空输入框内容
            ////客户端按钮颜色及bool重置
            for (int i = 0; i < m_alreadySelectedCli.Count; i++)
            {
                m_clientButtonDic[m_alreadySelectedCli[i]].m_buttonBg.GetComponent<UISprite>().color = Color.white;
                m_clientButtonDic[m_alreadySelectedCli[i]].m_isAdd = false;
            }
            //分组按钮颜色及bool重置
            IDictionaryEnumerator e = m_clientGroupDic.GetEnumerator();
            while (e.MoveNext())
            {
                GameObject groupButton;
                groupButton = (GameObject)e.Key;
                groupButton.GetComponent<ClickClientButton>().m_buttonBg.GetComponent<UISprite>().color = Color.white;
                groupButton.GetComponent<ClickClientButton>().m_isAdd = false;
            }
            m_alreadySelectedCli.Clear();
        }
    }

    /// <summary>
    /// 打开已连接客户端列表
    /// </summary>
    /// <param name="go"></param>
    void OpenClientList(GameObject go)
    {
        if (m_isShowClientList)
        {
            OpenClientList();
            if (!m_isShowCreatGroup)
                CloseCreatGroup();
        }

        else
        {
            CloseClientList();
        }
    }

    /// <summary>打开已连接客户端列表</summary>
    void OpenClientList()
    {
        MotionAestheticsScrp.AccLocalScaling(m_clientScroll, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_clientScroll, MABRANCH.SCALE).m_endCallback = ShowClient;
        m_openBtn.transform.Find("Label").GetComponent<UILabel>().text = "Close";
        m_isShowClientList = false;
    }

    /// <summary>关闭已连接客户端列表</summary>
    void CloseClientList()
    {
        m_clientList.gameObject.layer = LayerMask.NameToLayer("Default");
        MotionAestheticsScrp.AccLocalScaling(m_clientScroll, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_openBtn.transform.Find("Label").GetComponent<UILabel>().text = "Open";
        m_isShowClientList = true;
    }

    void ShowClient()
    {
        m_clientList.gameObject.layer = LayerMask.NameToLayer("UI");
    }

    /// <summary>
    /// 添加客户端ip至下拉列表
    /// </summary>
    /// <param name="str"></param>
    void AddClient(string str)
    {
        m_addClientIP = str;
    }

    /// <summary>
    /// 删除下拉列表客户端ip
    /// </summary>
    /// <param name="str">删除的客户端ip</param>
    void DeletClient(List<string> list)
    {
        for (int i = 0; i < list.Count; i++)
        {
            if (m_alreadySelectedCli.Contains(list[i]))
            {
                m_alreadySelectedCli.Remove(list[i]);
            }
        }
        m_deletClientIP = list;
    }

    /// <summary>选择所有客户端</summary>>
    void SelectAllClient(GameObject obj)
    {
        if (m_isSelect)
        {
            IDictionaryEnumerator e = m_clientButtonDic.GetEnumerator();
            while (e.MoveNext())
            {
                ClickClientButton clientButton;
                clientButton = (ClickClientButton)e.Value;
                clientButton.m_buttonBg.GetComponent<UISprite>().color = Color.red;
                if (!m_alreadySelectedCli.Contains(clientButton.m_clientIPLabel.text))
                    m_alreadySelectedCli.Add(clientButton.m_clientIPLabel.text);
                clientButton.m_isAdd = true;
            }
            m_isSelect = false;
        }
        else
        {
            IDictionaryEnumerator e = m_clientButtonDic.GetEnumerator();
            while (e.MoveNext())
            {
                ClickClientButton clientButton;
                clientButton = (ClickClientButton)e.Value;
                clientButton.m_buttonBg.GetComponent<UISprite>().color = Color.white;
                if (m_alreadySelectedCli.Contains(clientButton.m_clientIPLabel.text))
                    m_alreadySelectedCli.Remove(clientButton.m_clientIPLabel.text);
                clientButton.m_isAdd = false;
            }
            m_isSelect = true;
        }
    }

    /// <summary>打开创建组界面</summary>
    void OpenCreatGroup(GameObject obj)
    {
        if (m_isShowCreatGroup)
        {
            OpenCreatGroup();
        }

        else
        {
            CloseCreatGroup();
        }
    }

    /// <summary>打开创建分组界面</summary>
    void OpenCreatGroup()
    {
        SetButtonCollider(false);
        if (!m_isShowGroup)
            CloseGroup();
        if (!m_isShowClientList)
            CloseClientList();
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("Default");
        }
        m_information.GetComponent<UIPanel>().depth = 0;
        MotionAestheticsScrp.AccLocalScaling(m_groupingPanel, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_groupingPanel, MABRANCH.SCALE).m_endCallback = ShowInformatoin;
        m_isShowCreatGroup = false;
    }

    /// <summary>关闭创建分组界面</summary>
    void CloseCreatGroup()
    {
        SetButtonCollider(true);
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("Default");
        }
        m_information.GetComponent<UIPanel>().depth = 0;
        MotionAestheticsScrp.AccLocalScaling(m_groupingPanel, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_isShowCreatGroup = true;
    }

    /// <summary>展示创建组界面内信息</summary>
    void ShowInformatoin()
    {
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("UI");
        }
        m_information.GetComponent<UIPanel>().depth = 1;
    }

    /// <summary>打开分组</summary>
    void OpenGroup(GameObject obj)
    {
        if (m_isShowGroup)
        {
            OpenGroup();
            if (!m_isShowCreatGroup)
                CloseCreatGroup();
        }

        else
        {
            CloseGroup();
        }
    }

    /// <summary>打开分组</summary>
    void OpenGroup()
    {
        MotionAestheticsScrp.AccLocalScaling(m_clientGroupScroll, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_clientGroupScroll, MABRANCH.SCALE).m_endCallback = ShowGroup;
        m_groupBtn.transform.Find("Label").GetComponent<UILabel>().text = "Close";
        m_isShowGroup = false;
    }

    /// <summary>关闭分组</summary>
    void CloseGroup()
    {
        ClientGroupList.gameObject.layer = LayerMask.NameToLayer("Default");
        MotionAestheticsScrp.AccLocalScaling(m_clientGroupScroll, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_groupBtn.transform.Find("Label").GetComponent<UILabel>().text = "Open";
        m_isShowGroup = true;
    }

    void ShowGroup()
    {
        ClientGroupList.gameObject.layer = LayerMask.NameToLayer("UI");
    }

    /// <summary>创建分组</summary>
    void CreatGroup(GameObject obj)
    {
        List<Transform> list = m_selectClientGrid.GetChildList();
        List<string> clientList = new List<string>();
        if (list.Count > 0 && m_NameInput.value != "")
        {
            for (int i = 0; i < list.Count; i++)
            {
                //客户端按钮回原位
                m_groupClientGrid.AddChild(list[i]);
                //go.GetComponent<UIDragScrollView>().scrollView = m_groupClientScroll;
                m_selectClientGrid.repositionNow = true;
                m_groupClientGrid.repositionNow = true;
                list[i].GetComponent<GroupClickClientButton>().m_isSelect = false;
                //添加客户端IP
                clientList.Add(list[i].GetComponent<GroupClickClientButton>().m_clientIPLabel.text);
            }
            CloseCreatGroup();
            GameObject ob = NGUITools.AddChild(m_groupGrid.gameObject, m_clientButton);
            ClickClientButton ccb = ob.GetComponent<ClickClientButton>();
            ccb.m_clientIPLabel.text = m_NameInput.value;
            UIEventListener.Get(ccb.gameObject).onClick = ClickGroupClientItem;
            m_clientGroupDic.Add(ob, clientList);
            m_groupGrid.repositionNow = true;
            OpenGroup();
        }
    }

    /// <summary>点击客户端button</summary>
    void ClickGroupClientItem(GameObject go)
    {
        List<string> list = new List<string>();
        if (m_clientGroupDic.TryGetValue(go, out list))
        {
            ClickClientButton ccb = go.GetComponent<ClickClientButton>();
            if (ccb.m_isAdd)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (!m_alreadySelectedCli.Contains(list[i]))
                        m_alreadySelectedCli.Add(list[i]);
                }
            }
            else
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (m_alreadySelectedCli.Contains(list[i]))
                        m_alreadySelectedCli.Remove(list[i]);
                }
            }
        }
    }

    /// <summary>
    /// 设置button碰撞体
    /// </summary>
    /// <param name="bo">是否启用</param>
    void SetButtonCollider(bool bo)
    {
        for (int i = 0; i < m_buttonList.Count; i++)
        {
            m_buttonList[i].GetComponent<Collider>().enabled = bo;
        }
    }

    /// <summary>
    /// 当程序退出时关闭Socket及线程
    /// </summary>
    void OnApplicationQuit()
    {
        m_server.CloseNetwork();
    }
}
